package joshua.web.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import joshua.web.db.DbConnection;

public class UserThreadModel {
	
	public List<Map<String, Object>> getAllThread(){
		List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>() ; 
		try {
			ResultSet dbRes = DbConnection.executeQuery("SELECT * FROM user_thread ORDER BY updatetime DESC");
			while(dbRes.next()) {
				Map<String, Object> rec = new HashMap<String, Object>();
				rec.put("detail", dbRes.getString("detail"));
				rec.put("threadId", dbRes.getInt("threadid"));
				rec.put("updateDate", dbRes.getDate("updatetime"));
				rec.put("userName", dbRes.getString("username"));
				resList.add(rec);
			}
		} catch (SQLException e) {
			return null;
		}
		return resList;
	}
	
	
	public boolean addThread(String userName, String detail, Date updateDate) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sql = String.format("INSERT INTO user_thread (username, detail, updatetime) values ('%s', '%s', '%s')", 
								userName, detail, dateFormat.format(updateDate));
		try {
			DbConnection.executeSql(sql);
		} catch(SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	
	public boolean deleteThreadById(int threadId) {
		String sql = String.format("DELETE FROM user_thread WHERE threadid = %d", threadId);
		try {
			DbConnection.executeSql(sql);
		} catch(SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
